<template>
  <a-card title="📅 新建预定" class="booking-form-card">
    <a-alert
      v-if="errorMessage"
      :message="errorMessage"
      type="error"
      closable
      @close="errorMessage = ''"
      style="margin-bottom: 16px"
    />

    <a-form
      :model="formState"
      :rules="rules"
      layout="vertical"
      @finish="handleSubmit"
      ref="formRef"
    >
      <a-form-item label="会议室" name="room_id">
        <a-select
          v-model:value="formState.room_id"
          placeholder="选择会议室"
          size="large"
          @change="handleRoomChange"
        >
          <a-select-option
            v-for="room in rooms"
            :key="room.id"
            :value="room.id"
          >
            {{ room.name }} (容量: {{ room.capacity }})
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="日期" name="date">
        <a-date-picker
          v-model:value="formState.date"
          style="width: 100%"
          size="large"
          :disabled-date="disabledDate"
          autocomplete="off"
        />
      </a-form-item>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="开始时间" name="start_time">
            <a-time-picker
              v-model:value="formState.start_time"
              format="HH:mm"
              style="width: 100%"
              size="large"
              :disabled-hours="getDisabledHours"
              :disabled-minutes="getDisabledMinutes"
              :disabled="!formState.room_id || !formState.date"
              autocomplete="off"
              data-form-type="other"
              data-lpignore="true"
              data-1p-ignore
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="结束时间" name="end_time">
            <a-time-picker
              v-model:value="formState.end_time"
              format="HH:mm"
              style="width: 100%"
              size="large"
              :disabled-hours="getDisabledHours"
              :disabled-minutes="getDisabledMinutes"
              :disabled="!formState.room_id || !formState.date"
              autocomplete="off"
              data-form-type="other"
              data-lpignore="true"
              data-1p-ignore
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="预定人" name="booking_person">
        <a-input
          v-model:value="formState.booking_person"
          placeholder="请输入姓名"
          size="large"
          autocomplete="off"
        />
      </a-form-item>

      <a-form-item label="会议内容" name="meeting_content">
        <a-textarea
          v-model:value="formState.meeting_content"
          placeholder="请描述会议目的..."
          :rows="4"
          size="large"
          autocomplete="off"
        />
      </a-form-item>

      <a-form-item>
        <a-space>
          <a-button type="primary" html-type="submit" :loading="loading" size="large">
            提交预定
          </a-button>
          <a-button @click="handleReset" size="large">重置</a-button>
        </a-space>
      </a-form-item>
    </a-form>

    <!-- 日历预览 -->
    <a-divider>日历视图</a-divider>
    <a-calendar
      v-model:value="formState.date"
      :fullscreen="false"
    />
  </a-card>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { getRooms } from '@/services/roomService'
import { createBooking, checkAvailability } from '@/services/bookingService'
import { getRoomSchedule } from '@/services/scheduleService'

const emit = defineEmits(['booking-created'])

const formRef = ref(null)
const loading = ref(false)
const errorMessage = ref('')
const rooms = ref([])
const roomSchedule = ref(null)

const formState = reactive({
  room_id: undefined,
  date: dayjs(),
  start_time: null,
  end_time: null,
  booking_person: '',
  meeting_content: '',
})

const rules = {
  room_id: [{ required: true, message: '请选择会议室' }],
  date: [{ required: true, message: '请选择日期' }],
  start_time: [{ required: true, message: '请选择开始时间' }],
  end_time: [{ required: true, message: '请选择结束时间' }],
  booking_person: [{ required: true, message: '请输入预定人姓名' }],
  meeting_content: [{ required: true, message: '请输入会议内容' }],
}

const disabledDate = (current) => {
  // Disable past dates
  return current && current < dayjs().startOf('day')
}

// 获取会议室的时间表
const fetchRoomSchedule = async (roomId) => {
  if (!roomId) {
    roomSchedule.value = null
    return
  }
  
  try {
    const schedules = await getRoomSchedule(roomId)
    const dayOfWeek = formState.date.day()
    const schedule = schedules.find(s => s.day_of_week === dayOfWeek)
    roomSchedule.value = schedule
    
    if (schedule && !schedule.is_available) {
      message.warning('该会议室在选定日期不开放')
      formState.start_time = null
      formState.end_time = null
    }
  } catch (error) {
    console.error('获取时间表失败:', error)
    roomSchedule.value = null
  }
}

// 获取禁用的小时
const getDisabledHours = () => {
  if (!roomSchedule.value || !roomSchedule.value.is_available) {
    return Array.from({ length: 24 }, (_, i) => i)
  }
  
  const openHour = parseInt(roomSchedule.value.open_time.split(':')[0])
  const closeHour = parseInt(roomSchedule.value.close_time.split(':')[0])
  
  const disabled = []
  for (let i = 0; i < 24; i++) {
    if (i < openHour || i >= closeHour) {
      disabled.push(i)
    }
  }
  return disabled
}

// 获取禁用的分钟
const getDisabledMinutes = (selectedHour) => {
  if (!roomSchedule.value || !roomSchedule.value.is_available) {
    return Array.from({ length: 60 }, (_, i) => i)
  }
  
  // Parse open and close times more carefully
  const openTimeParts = roomSchedule.value.open_time.split(':').map(Number)
  const closeTimeParts = roomSchedule.value.close_time.split(':').map(Number)
  
  const openHour = openTimeParts[0]
  const openMinute = openTimeParts[1] || 0  // Default to 0 if not specified
  const closeHour = closeTimeParts[0]
  const closeMinute = closeTimeParts[1] || 0  // Default to 0 if not specified
  
  const disabled = []
  
  // 如果是开始的小时，禁用开始分钟之前的
  if (selectedHour === openHour) {
    // 当开放时间是 08:00:00 时，openMinute 是 0
    // 我们不应该禁用任何分钟，因为 08:00 是有效的开始时间（包含端点）
    // 只有当开放时间是 08:30:00 时，我们才应该禁用 0-29 分钟
    for (let i = 0; i < openMinute; i++) {
      disabled.push(i)
    }
  }
  
  // 如果是结束的小时，禁用结束分钟之后的（不包括结束分钟本身）
  if (selectedHour === closeHour) {
    // 当关闭时间是 18:00:00 时，closeMinute 是 0
    // 我们应该禁用分钟 1-59，但允许选择 0 分钟（18:00 是有效的结束时间）
    // 当关闭时间是 17:30:00 时，我们应该禁用 31-59 分钟，但允许选择 30 分钟
    for (let i = closeMinute + 1; i < 60; i++) {
      disabled.push(i)
    }
  }
  
  console.log(`Disabled minutes for hour ${selectedHour}:`, disabled);
  return disabled
}

// 监听会议室和日期变化
watch(() => formState.room_id, (newRoomId) => {
  fetchRoomSchedule(newRoomId)
})

watch(() => formState.date, () => {
  if (formState.room_id) {
    fetchRoomSchedule(formState.room_id)
  }
})

const handleRoomChange = () => {
  errorMessage.value = ''
  formState.start_time = null
  formState.end_time = null
}

const handleSubmit = async () => {
  loading.value = true
  errorMessage.value = ''

  try {
    // Combine date and time using local time
    const startDateTime = dayjs(formState.date)
      .hour(formState.start_time.hour())
      .minute(formState.start_time.minute())
      .second(0)

    const endDateTime = dayjs(formState.date)
      .hour(formState.end_time.hour())
      .minute(formState.end_time.minute())
      .second(0)

    // Debug logging
    console.log('Booking times:', {
      start: startDateTime.format('YYYY-MM-DD HH:mm:ss'),
      end: endDateTime.format('YYYY-MM-DD HH:mm:ss'),
      startTime: startDateTime.format('HH:mm:ss'),
      endTime: endDateTime.format('HH:mm:ss'),
      selectedStartHour: formState.start_time.hour(),
      selectedStartMinute: formState.start_time.minute(),
      selectedEndHour: formState.end_time.hour(),
      selectedEndMinute: formState.end_time.minute()
    });

    // 验证结束时间必须在开始时间之后
    if (endDateTime.isBefore(startDateTime) || endDateTime.isSame(startDateTime)) {
      errorMessage.value = '结束时间必须在开始时间之后'
      return
    }

    // Format datetime strings without timezone information
    // This ensures they are treated as local time by the backend
    const startStr = startDateTime.format('YYYY-MM-DDTHH:mm:ss')
    const endStr = endDateTime.format('YYYY-MM-DDTHH:mm:ss')
    
    console.log('Formatted time strings:', {
      start: startStr,
      end: endStr
    });

    // Check availability first
    const availabilityCheck = await checkAvailability({
      room_id: formState.room_id,
      start_time: startStr,  // No 'Z' suffix means local time
      end_time: endStr,      // No 'Z' suffix means local time
    })

    if (!availabilityCheck.available) {
      errorMessage.value = availabilityCheck.message
      console.log('Availability check failed:', availabilityCheck.message);
      console.log('Room schedule:', roomSchedule.value);
      return
    }

    // Create booking
    const bookingData = {
      room_id: formState.room_id,
      booking_person: formState.booking_person,
      meeting_content: formState.meeting_content,
      start_time: startStr,  // No 'Z' suffix means local time
      end_time: endStr,      // No 'Z' suffix means local time
    }

    await createBooking(bookingData)
    message.success('预定创建成功！')
    
    handleReset()
    emit('booking-created')
  } catch (error) {
    errorMessage.value = error.response?.data?.detail || '预定创建失败'
    console.error('Booking error:', error);
    console.log('Form state at error:', formState);
  } finally {
    loading.value = false
  }
}

const handleReset = () => {
  formRef.value?.resetFields()
  formState.date = dayjs()
  formState.start_time = null
  formState.end_time = null
  errorMessage.value = ''
}

const fetchRooms = async () => {
  try {
    rooms.value = await getRooms()
  } catch (error) {
    message.error('加载会议室列表失败')
  }
}

onMounted(() => {
  fetchRooms()
})
</script>

<style scoped>
.booking-form-card {
  height: 100%;
}
</style>
